﻿using System;
using System.Globalization;

namespace Gmantis.Controls.DataGrid
{
    public class DataGridDateTimeConverter : DataGridBoundConverter
    {
        public override object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if ((value != null) && (value.GetType().GetNonNullableType() != typeof(DateTime)))
            {
                value = this.ConvertBack(value, typeof(DateTime), parameter, culture);
            }
            if (targetType != typeof(double))
            {
                return base.Convert(value, targetType, parameter, culture);
            }
            if (value.GetType().IsNullableType())
            {
                DateTime? nullable = value as DateTime?;
                return (nullable.HasValue ? ((double)nullable.Value.Ticks) : (double)1.0 / (double)0.0);
            }
            DateTime time2 = (DateTime)value;
            return (double)time2.Ticks;
        }

        public override object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if ((targetType.GetNonNullableType() == typeof(DateTime)) && (value is string))
            {
                DateTime time;
                if ((parameter is string) && DateTime.TryParseExact((string)value, (string)parameter, culture.DateTimeFormat, DateTimeStyles.None, out time))
                {
                    return time;
                }
                if (DateTime.TryParse((string)value, out time))
                {
                    return time;
                }
                return null;
            }
            if ((targetType.GetNonNullableType() != typeof(DateTime)) || !(value is double))
            {
                return value;
            }
            double d = (double)value;
            if (targetType.IsNullableType())
            {
                return (double.IsNaN(d) ? null : ((DateTime?)new DateTime(Math.Max(DateTime.MinValue.Ticks, Math.Min(DateTime.MaxValue.Ticks, (long)d)))));
            }
            return (double.IsNaN(d) ? DateTime.MinValue : new DateTime((long)d));
        }
    }
}
